import { 
  ROUTE_HISTORY_KEY, 
  MAX_HISTORY_COUNT,
  AUTH_REQUIRED_PATHS,
  AUTH_FREE_PATHS,
  DEFAULT_ROUTE_META 
} from './constants';

/**
 * 路由工具类
 */
export class RouteUtils {
  /**
   * 获取路由历史记录
   * @returns {Array} 路由历史记录数组
   */
  static getRouteHistory() {
    try {
      const historyStr = localStorage.getItem(ROUTE_HISTORY_KEY);
      return historyStr ? JSON.parse(historyStr) : [];
    } catch (error) {
      console.error('获取路由历史记录失败:', error);
      return [];
    }
  }

  /**
   * 保存路由历史记录
   * @param {Object} historyItem - 路由历史记录项
   */
  static saveRouteHistory(historyItem) {
    try {
      const history = this.getRouteHistory();
      const existingIndex = history.findIndex(item => item.path === historyItem.path);
      
      if (existingIndex !== -1) {
        // 更新现有记录
        history[existingIndex] = historyItem;
      } else {
        // 添加新记录
        history.unshift(historyItem);
      }
      
      // 限制历史记录数量
      if (history.length > MAX_HISTORY_COUNT) {
        history.splice(MAX_HISTORY_COUNT);
      }
      
      localStorage.setItem(ROUTE_HISTORY_KEY, JSON.stringify(history));
    } catch (error) {
      console.error('保存路由历史记录失败:', error);
    }
  }

  /**
   * 清除路由历史记录
   */
  static clearRouteHistory() {
    try {
      localStorage.removeItem(ROUTE_HISTORY_KEY);
    } catch (error) {
      console.error('清除路由历史记录失败:', error);
    }
  }

  /**
   * 检查路径是否需要登录验证
   * @param {string} path - 路径
   * @returns {boolean} 是否需要登录
   */
  static isAuthRequired(path) {
    return AUTH_REQUIRED_PATHS.some(authPath => 
      path === authPath || path.startsWith(authPath + '/')
    );
  }

  /**
   * 检查路径是否不需要登录验证
   * @param {string} path - 路径
   * @returns {boolean} 是否不需要登录
   */
  static isAuthFree(path) {
    return AUTH_FREE_PATHS.some(freePath => 
      path === freePath || path.startsWith(freePath + '/')
    );
  }

  /**
   * 获取路由的完整路径
   * @param {Object} route - 路由配置
   * @param {string} parentPath - 父路径
   * @returns {string} 完整路径
   */
  static getFullPath(route, parentPath = '') {
    const currentPath = parentPath + route.path;
    
    if (route.routes && route.routes.length > 0) {
      return route.routes.map(subRoute => 
        this.getFullPath(subRoute, currentPath)
      ).join(',');
    }
    
    return currentPath;
  }

  /**
   * 根据路径查找路由配置
   * @param {Array} routes - 路由配置数组
   * @param {string} targetPath - 目标路径
   * @returns {Object|null} 找到的路由配置
   */
  static findRouteByPath(routes, targetPath) {
    for (const route of routes) {
      if (route.path === targetPath) {
        return route;
      }
      
      if (route.routes) {
        const found = this.findRouteByPath(route.routes, targetPath);
        if (found) return found;
      }
    }
    
    return null;
  }

  /**
   * 获取路由的元信息
   * @param {Object} route - 路由配置
   * @returns {Object} 路由元信息
   */
  static getRouteMeta(route) {
    return {
      ...DEFAULT_ROUTE_META,
      ...route.meta,
    };
  }

  /**
   * 将路由配置转换为菜单项
   * @param {Array} routes - 路由配置数组
   * @returns {Array} 菜单项数组
   */
  static routesToMenuItems(routes) {
    return routes
      .filter(route => !route.hideInMenu && !route.redirect)
      .map(route => ({
        key: route.path,
        label: route.name || route.path,
        icon: route.icon,
        path: route.path,
        meta: route.meta,
        children: route.routes ? this.routesToMenuItems(route.routes) : undefined,
        type: route.routes && route.routes.length > 0 ? 'subMenu' : 'item',
      }));
  }

  /**
   * 获取面包屑路径
   * @param {Array} routes - 路由配置数组
   * @param {string} currentPath - 当前路径
   * @returns {Array} 面包屑路径数组
   */
  static getBreadcrumbPaths(routes, currentPath) {
    const breadcrumbs = [];
    
    const findBreadcrumb = (routeList, path) => {
      for (const route of routeList) {
        if (route.path === path) {
          breadcrumbs.unshift(route);
          return true;
        }
        
        if (route.routes) {
          if (findBreadcrumb(route.routes, path)) {
            if (!route.hideInBreadcrumb) {
              breadcrumbs.unshift(route);
            }
            return true;
          }
        }
      }
      return false;
    };
    
    findBreadcrumb(routes, currentPath);
    return breadcrumbs;
  }

  /**
   * 检查用户是否有访问路由的权限
   * @param {Object} route - 路由配置
   * @param {Array} userPermissions - 用户权限数组
   * @returns {boolean} 是否有权限
   */
  static hasRouteAccess(route, userPermissions = []) {
    if (!route.access) return true;
    
    // 这里可以根据实际的权限系统进行扩展
    return userPermissions.includes(route.access);
  }

  /**
   * 过滤有权限的路由
   * @param {Array} routes - 路由配置数组
   * @param {Array} userPermissions - 用户权限数组
   * @returns {Array} 过滤后的路由配置数组
   */
  static filterAccessibleRoutes(routes, userPermissions = []) {
    return routes
      .filter(route => this.hasRouteAccess(route, userPermissions))
      .map(route => ({
        ...route,
        routes: route.routes ? this.filterAccessibleRoutes(route.routes, userPermissions) : undefined,
      }));
  }

  /**
   * 获取当前路由信息
   * @returns {Object} 当前路由信息
   */
  static getCurrentRouteInfo() {
    return {
      pathname: window.location.pathname,
      search: window.location.search,
      hash: window.location.hash,
      query: new URLSearchParams(window.location.search),
    };
  }

  /**
   * 安全的路由跳转
   * @param {string} path - 目标路径
   * @param {Object} state - 状态数据
   */
  static safePush(path, state) {
    try {
      // 如果使用了React Router，这里可以调用history.push
      // 否则使用window.location
      if (window.history && window.history.pushState) {
        window.history.pushState(state, '', path);
        // 触发popstate事件，让React Router知道路由变化
        window.dispatchEvent(new PopStateEvent('popstate'));
      } else {
        window.location.href = path;
      }
    } catch (error) {
      console.error('路由跳转失败:', error);
      // 降级处理：使用 window.location
      window.location.href = path;
    }
  }

  /**
   * 安全的路由替换
   * @param {string} path - 目标路径
   * @param {Object} state - 状态数据
   */
  static safeReplace(path, state) {
    try {
      if (window.history && window.history.replaceState) {
        window.history.replaceState(state, '', path);
        // 触发popstate事件，让React Router知道路由变化
        window.dispatchEvent(new PopStateEvent('popstate'));
      } else {
        window.location.replace(path);
      }
    } catch (error) {
      console.error('路由替换失败:', error);
      // 降级处理：使用 window.location
      window.location.replace(path);
    }
  }

  /**
   * 设置页面标题
   * @param {string} title - 页面标题
   */
  static setPageTitle(title) {
    if (title) {
      document.title = title;
    }
  }

  /**
   * 设置页面元信息
   * @param {Object} meta - 元信息对象
   */
  static setPageMeta(meta) {
    if (meta.title) {
      this.setPageTitle(meta.title);
    }
    
    if (meta.description) {
      let metaDescription = document.querySelector('meta[name="description"]');
      if (!metaDescription) {
        metaDescription = document.createElement('meta');
        metaDescription.name = 'description';
        document.head.appendChild(metaDescription);
      }
      metaDescription.content = meta.description;
    }
    
    if (meta.keywords && meta.keywords.length > 0) {
      let metaKeywords = document.querySelector('meta[name="keywords"]');
      if (!metaKeywords) {
        metaKeywords = document.createElement('meta');
        metaKeywords.name = 'keywords';
        document.head.appendChild(metaKeywords);
      }
      metaKeywords.content = meta.keywords.join(', ');
    }
  }
}
